﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using MadeInPortugal.Class;
using System.Collections;
using MadeInPortugal;

namespace MadeInPortugalWebApplication
{
    public partial class Users : System.Web.UI.Page
    {
        bool[] rowChanged;

        Enterprise _srv = new Enterprise();
        ArrayList userListSource = new ArrayList();
        DataTable dtPages;

        public int CurrentPage
        {
            get { return int.Parse(hfPageNumber.Value); }
            set { hfPageNumber.Value = value.ToString(); ; }
        }

        public int PageSize
        {
            get;
            set;
        }

        public DataTable DtPages
        {
            get
            {
                if (dtPages == null)
                {
                    dtPages = new DataTable();
                    dtPages.Columns.Add("Class");
                    dtPages.Columns.Add("PageNumber");
                }
                return dtPages;
            }
            set
            {
                if (value != null)
                    dtPages = value;
            }
        }

        protected override void OnInit(EventArgs e)
        {
            if ((Session["UserType"] == null) || (Session["UserType"].ToString() != "Admin"))
                Response.Redirect("index.aspx");
            base.OnInit(e);
            PageSize = 12;
            if (!IsPostBack)
            {
                userListSource.AddRange(_srv.GetAllUsers());
                int intermCount = ((CurrentPage) * PageSize > userListSource.Count) ? (userListSource.Count - (CurrentPage - 1) * PageSize) : PageSize;
                userGridView.DataSource = userListSource.GetRange((CurrentPage - 1) * PageSize, intermCount);
                userGridView.DataBind();
            }
            else
            {
                userListSource = (ArrayList)Session["userlist"];
            }

            DtPages = (DataTable)ViewState["pages"];


        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            int totalRows = userGridView.Rows.Count;
            rowChanged = new bool[totalRows];

            BuildPagination();
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            if (Page.IsPostBack)
            {
                int totalRows = userGridView.Rows.Count;
                for (int r = 0; r < totalRows; r++)
                {
                    if (rowChanged[r])
                    {
                        GridViewRow thisGridViewRow = userGridView.Rows[r];
                        Label lbPk = (Label)thisGridViewRow.FindControl("lbNumber");
                        int pk = int.Parse(lbPk.Text);
                        TextBox edittbxMaxItems = (TextBox)thisGridViewRow.FindControl("tbxMaxItems");
                        string maxItems = edittbxMaxItems.Text;
                        TextBox editcbOpenNewWindow = (TextBox)thisGridViewRow.FindControl("cbOpenNewWindow");
                        string isOpenNewWindow = editcbOpenNewWindow.Text;


                        Enterprise updated = _srv.Update(new Enterprise() { Id = pk, Name = maxItems, EnterpriseName = isOpenNewWindow });

                        if (updated != null)
                        {
                            SetFeedBack(string.Format("O utilizador '{0}' foi actualizado com sucesso.", updated.EnterpriseName), Messages.FeedBackType.success);
                        }
                        else
                        {
                            SetFeedBack(string.Format("Ocorreu um erro ao actualizar o utilizador '{0}'.", updated.EnterpriseName), Messages.FeedBackType.error);
                        }

                        userListSource.Clear();
                        userListSource.AddRange(_srv.GetAllUsers());
                    }
                }
            }

            int intermCount = ((CurrentPage) * PageSize > userListSource.Count) ? (userListSource.Count - (CurrentPage - 1) * PageSize) : PageSize;
            userGridView.DataSource = userListSource.GetRange((CurrentPage - 1) * PageSize, intermCount);
            userGridView.DataBind();

            BuildPagination();

            ViewState["pages"] = DtPages;
            Session["userlist"] = userListSource;
        }


        protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("Save"))
            {
                int row;
                if (int.TryParse(e.CommandArgument.ToString(), out row))
                    rowChanged[row] = true;
            }
        }

        protected void RepeaterChangePage_Command(object sender, RepeaterCommandEventArgs e)
        {
            if (e.CommandName.Equals("goPage"))
            {
                int pageSelected = 1;
                if (int.TryParse(e.CommandArgument.ToString(), out pageSelected))
                {
                    CurrentPage = pageSelected;
                }
            }
        }

        protected string GetUserName(object Id)
        {
            string ret = string.Empty;
            foreach (Enterprise item in userListSource)
            {
                
                if (item.Id == int.Parse(Id.ToString()))
                {
                    ret = item.Name;
                    break;
                }
            }

            return ret;
        }

        private void BuildPagination()
        {
            DtPages.Clear();
            if (userListSource.Count > PageSize)
            {
                int intermediateCount = 0;
                while (intermediateCount < userListSource.Count)
                {
                    int pageNr = intermediateCount / PageSize + 1;

                    DataRow dr = DtPages.NewRow();
                    dr["Class"] = (pageNr == CurrentPage ? "current" : string.Empty);
                    dr["PageNumber"] = pageNr;
                    DtPages.Rows.Add(dr);

                    intermediateCount += PageSize;
                }

                paginationList.DataSource = DtPages;
                paginationList.DataBind();
            }
        }

        private void SetFeedBack(string htmlMessage, Messages.FeedBackType fType)
        {
            feedbackPanel.InnerHtml = htmlMessage;
            feedbackPanel.Attributes.Add("class", fType.ToString());
        }
    }
}

